package com.example.spring.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

/**
 * 2017-05-24
 * @author wqlin
 *
 */
public class LoginFilter extends ZuulFilter{
    private static Logger log = LoggerFactory.getLogger(LoginFilter.class);


    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 1;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();

        Object accessToken = request.getParameter("token");
        if(null == accessToken){
            log.warn("token is empty");
            ctx.setSendZuulResponse(false);
            ctx.setResponseStatusCode(401);
            try {
                ctx.getResponse().getWriter().write("token is empty");
            }catch (Exception e){}

            return null;
        }

        Cookie[] cookies = request.getCookies();

        //System.out.println(cookies[0].getComment());
        //System.out.println(cookies.toString());
        log.info("token is ok");
        StringBuffer sb = new StringBuffer();
        sb.append("\r\n=====================================================================\r\n");
        sb.append("\r\n                 WELCOME SPRING CLOUD                  \r\n");
        sb.append("\r\n=====================================================================\r\n");
        System.out.println(sb.toString());
        return null;
    }
}
